//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "CQBTraining\main.sqf"
#include <functions\core_macros.h>

TRACE("Start");
TMFPROFILERSTART;

private ["_size","_rectangle","_targets","_walls"];

QGVAR(pveh) addPublicVariableEventHandler FUNC(runEvent);
GVAR(ObjectStore) = "Land_HelipadEmpty_F" createVehicleLocal [0,0,0];
GVAR(ObjectStore) allowDamage false;


if (markerType "CQB_Training_Ground" != "") then {
	GVAR(CQB_POS) = markerPos "CQB_Training_Ground";
	GVAR(CQB_POS) set [2,0];
	_size = markerSize "CQB_Training_Ground";
	_rectangle = (markerShape "CQB_Training_Ground" == "RECTANGLE");
	GVAR(CQB_SIZE) = (_size select 0) max (_size select 1);
	"CQB_Training_Ground" setMarkerAlpha 0;
};

TRACE_1("Adding Events",QUOTE(FUNC(registerEvent)));
[0,"AddScore",FUNC(addScore)] call FUNC(registerEvent);
[1,"ResetScores",FUNC(resetScores)] call FUNC(registerEvent);
[1,"ResetTargets",FUNC(resetTargets)] call FUNC(registerEvent);
[0,"SkipTime",FUNC(skipTime)] call FUNC(registerEvent);
[0,"RepopTargets",{
	GVAR(CQB_RePop) = !GVAR(CQB_RePop);
	if (!isDedicated) then { if (GVAR(CQB_RePop)) then { hint localize "STR_CQB_REPOP_TARGETS";} else { hint localize "STR_CQB_NOREPOP_TARGETS";} };
}] call FUNC(registerEvent);

if ((GVAR(CQB_POS) distance [0,0,0]) > 0) then {
	if (isServer) then {
		GVAR(CQB_Targets) = nearestObjects [GVAR(CQB_POS), ["TargetP_Inf_F"], GVAR(CQB_SIZE)];
		TRACE_1("Targets",count GVAR(CQB_Targets));
		{
			_x addEventHandler ["HandleDamage", FUNC(targetShot)];
		} foreach GVAR(CQB_Targets);
		_walls = nearestObjects [GVAR(CQB_POS), ["Land_Shoot_House_Wall_F","Land_Pallet_F"], GVAR(CQB_SIZE)];
		TRACE_1("Walls",count _walls);
		{
			_x addEventHandler ["HandleDamage", {0}];
		} foreach _walls;
		[] spawn FUNC(checkTargets);
	};
	
	if (!isDedicated) then {
		["PLAYER_HANDLEDAMAGE",FUNC(playerShot)] call tyr_fnc_addHandler;
		_control_center = missionNamespace getVariable ["CQB_ControlCenter",objNull];
		if (!isnull _control_center) then {
			[_control_center,localize "STR_CQB_CC_ACTION",{createDialog "CQB_ui_control";}] call FUNC(addAction);
		};
		GVAR(ZONE_TRIGGER) = createTrigger["EmptyDetector" ,GVAR(CQB_POS)];
		GVAR(ZONE_TRIGGER) setTriggerArea [GVAR(CQB_SIZE), GVAR(CQB_SIZE), 0, false];
		GVAR(ZONE_TRIGGER) setTriggerActivation ["ANY", "PRESENT", true];
		GVAR(ZONE_TRIGGER) setTriggerTimeout [5, 5, 5, true];
		GVAR(ZONE_TRIGGER) setTriggerStatements["player in thisList", "player allowDamage false; player setCaptive true;", "player allowDamage true; player setCaptive false;"];

	};
} else {
	ERROR("CQB_Training_Ground marker not found!"),
};
TRACE("End");
TMFPROFILERSTOP;